package com.lbh.cloudgallery.front;

import com.lbh.cloudgallery.entity.ProductEntity;
import com.lbh.cloudgallery.entity.vo.SearchProductVo;
import com.lbh.cloudgallery.service.ProductService;
import com.xxx.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 
 *
 * @author 廖碧涵
 * @email lbh@qq.com
 * @date 2021-02-25 22:47:51
 */
@Api(tags = "前台-商品模块")
@RestController
@RequestMapping("front/product")
public class FrontProductController {
    @Autowired
    private ProductService productService;

    /**
     * 查询所有商品
     */
    @ApiOperation(value = "查询所有商品")
    @GetMapping("/list")
    public R list(){
        List<ProductEntity> list = productService.list();
        return R.ok().put("items", list);
    }


    /**
     * 根据商品id查询商品数据
     */
    @ApiOperation(value = "据id查商品")
    @GetMapping("/infoById/{id}")
    public R getInfoById(@ApiParam(name = "id",value = "商品id") @PathVariable("id") Long id){
		ProductEntity product = productService.getById(id);
        return R.ok().put("product", product);
    }

    /**
     * 聚合查询
     * @param searchProductVo vo对象
     * @return
     */
    @ApiOperation("聚合查询")
    @PostMapping("/info")
    public R getInfo(@RequestBody SearchProductVo searchProductVo) {
        List<ProductEntity> list = productService.searchProduct(searchProductVo);
        return R.ok().put("items", list);
    }

    /**
     * 发布商品
     */
    @ApiOperation(value = "发布商品")
    @PostMapping("/save")
    public R save(@RequestBody ProductEntity product){
        product.setGmtCreate(new Date());
        product.setGmtModified(new Date());
		productService.save(product);

        return R.ok();
    }

    /**
     * 修改
     */
    @ApiOperation(value = "基础修改")
    @PostMapping("/update")
    public R update(@RequestBody ProductEntity product){
        product.setGmtModified(new Date());
        boolean flag = productService.updateById(product);
        if(flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除 >=1 个商品
     */
    @ApiOperation(value = "基础删除")
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		productService.removeByIds(Arrays.asList(ids)); // 数组转List，传入方法

        return R.ok();
    }


    @ApiOperation(value ="立即购买")
    @DeleteMapping("/toOrder")
    public R toOrder(@RequestParam Integer productId,@RequestParam Integer count){
        String s = productService.createFromCart(productId,count);
        return R.ok().put("msg", s);
    }

}
